'use strict'
/**
 * Created by wangxd on 2017/3/13.
 */
const PORT = 1234;
const CONNECTON_STRING = '127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183';
const REGISTRY_ROOT = '/registry';

let express = require('express');
let zookeeper = require('node-zookeeper-client');
let httpProxy = require('http-proxy');

let zk = zookeeper.createClient(CONNECTON_STRING);
zk.connect();

let proxy = httpProxy.createProxyServer();
proxy.on('error',function(err,req,res){
	res.end();
});

let app = express();

app.use(express.static('public'));
app.all('*', function(req,res){

	if (req.path === '/favicon.ico') {
		res.end();
		return ;
	}

	//获取服务名称
	let serviceName = req.get('Service-Name');
	console.log('service name: %s', serviceName);
	if (!serviceName) {
		console.log('Service-Name request header is not exist.');
		res.end();
		return ;
	}

	// 获取服务路径
	let servicePath = REGISTRY_ROOT + '/' + serviceName;
	console.log('servicePath:%s',servicePath);
	
	// 获取服务路径下的地址
	zk.getChildren(servicePath, function(error,addressNodes){
		if (error) {
			console.log(error.stack);
			res.end();
			return ;
		}

		let size = addressNodes.length;
		if (size === 0) {
			console.log('address %s is not exist',servicePath);
			res.end();
			return ;
		}

		// 生成路径
		var addressPath = servicePath + '/';
		if (size === 1) {
			addressPath += addressNodes[0];
		}else{
			addressPath += addressNodes[parseInt(Math.random() * size)];
		}
		console.log('addressPath is %s',addressPath);

		// 获取服务地址
		zk.getData(addressPath, function(error,serviceAddress){
			if (error) {
				console.log(error.stack);
				res.end();
				return ;
			}
			console.log('serviceAddress is %s',serviceAddress);
			if (!serviceAddress) {
				console.log('service address is not exist.');
				res.end();
				return ;
			}

			// 执行反向代理
			proxy.web(req,res,{
				target: 'http://' + serviceAddress
			});
		});

	});
});

app.listen(PORT,function(){
	console.log('service is running at %d',PORT);
});